/**
 *
 */
layui.define(["jquery", 'layer', 'element', 'upload', 'admin', 'view'], function (exports) {
    const {$, layer, element, setter, admin} = layui;
    const defaultPic = "./admin/img/default-pic.jpg",
        fileUpload = setter.request.apiUrl + '/upload',
        Tpl = {
            morePic() {
                return '<button type="button" class="layui-btn uploadBtn"><i class="layui-icon layui-icon-upload"></i></button>\n' +
                    '   <blockquote class="input-group layui-elem-quote layui-quote-nm" style="margin-top: 10px;">\n' +
                    '        <ul class="layui-clear layui-upload-box"></ul>\n' +
                    '</blockquote>';
            },
            singlePic(name) {
                return '<input type="text" class="layui-input" name="'+name+'" style="width: 65%;float: left;">\n' +
                    '   <button type="button" class="layui-btn uploadBtn"><i class="layui-icon layui-icon-upload"></i></button>\n' +
                    '   <button type="button" class="layui-btn layui-btn-normal selectBtn"><i class="layui-icon layui-icon-align-center"></i></button>\n' +
                    '   <div class="input-group">\n' +
                    '       <ul class="layui-upload-box"></ul>\n' +
                    '</div>';
            },
            previewTpl(index) {
                return '<li id="id-'+index+'">\n ' +
                    '      <img alt=""> <i class="layui-icon layui-icon-delete icon-delete" id="picDelBtn"></i>\n ' +
                    '      <div class="layui-progress" lay-showpercent="yes" lay-filter="uploadProgress_' + index + '">\n' +
                    '          <div class="layui-progress-bar" lay-percent=""></div>\n ' +
                    '      </div>\n' +
                    '</li>';
            },
            initTpl(thumbs, options) {
                let uploadTpl = '';
                layui.each(thumbs, function (index, item) {
                    uploadTpl += '<li>\n <img lay-src="'+AppGeneral.storage(item)+'" src="'+defaultPic+'" alt="">\n <i class="layui-icon layui-icon-delete icon-delete" id="picDelBtn"></i>\n';
                    if (options.multiple) {
                        uploadTpl += '<input type="hidden" name="'+options.name+'[]" value="'+item+'">\n';
                    }
                    uploadTpl += '</li>';
                });
                return uploadTpl;
            },
        };
    let defaults = {
        elem: '.openThumb',
        name: 'thumb',
        multiple: false,
        limit: 5,
        csrfToken: AppGeneral.localStorage.getItem('TOKEN')
    };

    exports("fileUpload", {
        init(options) {
            options = $.extend(defaults, options);
            $(options.elem).html(options.multiple ? Tpl.morePic() : Tpl.singlePic(options.name));
            this.options = options;
            this.uploadImagesEvent();
            this.selectBtn();
            if (options.value) {
                this.update(options.value);
            }
            return this;
        },

        update(thumb) {
            if (thumb && typeof thumb === 'string') {
                const options = this.options, thumbs = options.multiple ? JSON.parse(thumb) : [thumb];
                if (!options.multiple) {
                    $(options.elem).find("input[name="+options.name+"]").val(thumb);
                }
                const upload_box = $(options.elem).find('.input-group .layui-upload-box').html(Tpl.initTpl(thumbs, options));
                this.resetImg(upload_box);
            }
            return false;
        },

        uploadImagesEvent() {
            if (!this.options) return false;
            const options = this.options, upload_box = $(options.elem).find('.input-group .layui-upload-box');
            layui.upload.render({
                elem: '.uploadBtn',
                url: fileUpload,
                acceptMime: 'image/*',
                field: 'file',
                headers: {
                    Authorization: 'Bearer '+ options.csrfToken
                },
                multiple: options.multiple,
                before: function (obj) {
                    obj.preview(function(index, file, result) {
                        options.multiple ? upload_box.append(Tpl.previewTpl(index, result)) : upload_box.html(Tpl.previewTpl(index, result));
                        element.progress('uploadProgress_' + index, '0%');
                    });
                },
                done: function (res, index, upload) {
                    if (res.code === 200) {
                        let data = res.data;
                        upload_box.find("#id-"+index).find('img').attr("src", AppGeneral.storage(data.file_path));
                        options.multiple
                            ? upload_box.find("#id-"+index).append('<input type="hidden" name="'+options.name+'[]" value="'+data.file_path+'">')
                            : $(options.elem).find("input[name="+options.name+"]").val(data.file_path);
                        return true;
                    }
                    layer.msg(res.message);
                },
                progress: function(n, elem, res, index){
                    element.progress('uploadProgress_' + index, n + '%');
                    if (n === 100) {
                        setTimeout(function () {
                            upload_box.find("#id-"+index).find(".layui-progress").remove();
                        }, 800);
                    }
                },
                error: function(index, upload){
                    upload_box.find("#id-"+index).remove();
                }
            });
        },

        selectBtn() {
           $('.selectBtn').on('click', function () {
               const view = layui.view;
               admin.popup({
                   title: '选择附件',
                   area: ['75%', '580px'],
                   id: 'LAY-popup-files-select-show',
                   btn: false,
                   btnAlign: 'c',
                   success: function() {
                       view(this.id).render('content/attachment/select', {
                           mode: 'images'
                       })
                   },
                   yes: function(index, layero) {
                       console.log(index, layero);
                   }
               });
           })
        },

        resetImg(elem) {
            if (!elem) return false;
            const that = this;
            that.lazyImg(elem);
            elem.on('click', 'img', function(){
                layer.photos({
                    photos: { title: "查看", data: [{ src: $(this).attr('src') }] },
                    shade: .01,
                    closeBtn: 1,
                    anim: 5
                });
            });
            elem.on('click', "#picDelBtn", function () {
                that.delImage(this);
            });
        },

        lazyImg(elem) {
            if (!elem) return false;
            elem.find('img').each(function () {
                const Img = $(this);
                AppGeneral.loadImage(Img.attr('lay-src')).then(img => {
                    Img.attr('src', img.src).removeAttr("lay-src");
                });
            });
        },

        delImage(elem) {
            if (this.options && elem) {
                const options = this.options;
                layer.confirm('确认删除吗？', {icon: 3}, function(index){
                    if (!options.multiple) {
                        $(elem).parents(".layui-upload").find("input[name="+options.name+"]").val("");
                    }
                    $(elem).parent().remove();
                    layer.close(index);
                });
            }
        },
    });
});
